<?php
/**
 * Created by PhpStorm.
 * User: guobao
 * Date: 2018/6/18
 * Time: 15:00
 */

namespace menghe\model;
use PDO;
use PDOException;

class Base
{
    private static $pdo;
    private $table;//数据表
    private $where = '';
    private $field = '*';//指定列数据
    private $order= '';//排序
    /**
     * 连接数据库
     */
    public function __construct($table)
    {
        $this->table=strtolower(explode('\\',$table)[2]);
        $this->connect();
    }
    private function connect(){
        $dsn = 'mysql:host='.config("database.host").';dbname='.config("database.dbname");
        if(is_null(self::$pdo)){
            try{
                //连接数据库
                $username = config('database.user');
                $password = config('database.password');
                self::$pdo=new PDO($dsn,$username,$password);
                //设置字符集
                self::$pdo->query('set names utf8');
                //设置错误属性
                self::$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            }catch(PDOException $exception){
                echo $exception->getMessage();
                exit;
            }
        }
    }
    /**
     * @param $sql有结果集
     */
    public function query($sql){
//        p($sql);select * from stu
        try{
            return  self::$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        }catch(PDOException $exception){
            echo $exception->getMessage();
            exit;
        }
    }

    /**
     * 无结果集操作
     * @param $sql
     * @return mixed
     */
    public function exec($sql){
        try{
            $afRows = self::$pdo->exec($sql);
            return $afRows;
        }catch(PDOException $exception){
            echo $exception->getMessage();
            exit;
        }
    }
    /**
     *获取所有数据
     */
    public function getAll()
    {
        $sql = "SELECT {$this->field} FROM {$this->table}{$this->where}{$this->order}";
//        p($sql);die;
        return $this->query($sql);
    }
    /**
     * 条件查询
     */
    public function where($where){
//        p($where);die;
        $this->where=' where '.$where;
        return $this;

    }
    /**
     * 排序方法
     */
    public function orderBy($order){
        $this->order = ' order by '. $order;
        return $this;
    }
    /**
     * 指定列查询
     */
    public function field($field){
        //4
        $this->field = $field;
        return $this;
    }
    /**
     * 写入方法
     */
    public function insert($data){
//        p($data);
        $field = array_keys($data);
        $field = implode(',',$field);
//        p($field);
        $values = array_values($data);
        $values ="'" .implode("','",$values)."'";
//        p($values);
        $sql ="INSERT INTO {$this->table} ({$field}) VALUES ({$values})";
//        p($sql);
        return $this->exec($sql);
    }
    /**
     * 查询方法
     */
    public function find($primary){
        $pk = $this->get_pri();
//        p($pk);
        $sql = "SELECT * FROM {$this->table} WHERE {$pk}={$primary}";
        return $this->query($sql);
    }
    /**
     * 更新方法
     */
    public function update($data){
        p($data);die;
//      update stu set username='zhangguobao'  where id=1;
        if(!$this->where) return false;
        $fields = '';
        foreach($data as $k=>$v){
            $fields .=$k.'='.(is_int($v)?$v:"'$v'").',';
        }
        $fields = rtrim($fields,',');
        $sql = "UPDATE {$this->table} SET {$fields} {$this->where}";
        return $this->exec($sql);
    }
    /**
     * 获取主键字段
     */
    private function get_pri(){
        $sql = "DESC {$this->table}";
        $result = $this->query($sql);
//        p($result);die;
        foreach($result as $v){
            if($v['Key']=='PRI'){
                $pk = $v['Field'];
                break;
            }
        }
        return $pk;
    }

}